package app.caihan.wanandroid.viewmodel

import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import app.caihan.wanandroid.base.WanBaseViewModel
import app.caihan.wanandroid.model.ScWanAndroidFactory
import app.caihan.wanandroid.model.bean.PageList
import com.scwang.smart.refresh.layout.api.RefreshLayout

/**
 *
 *
 * @author Seven-C
 * @date 2020/8/9
 */
class ArticleListUiModel : WanBaseViewModel() {
    private val repository by lazy { ScWanAndroidFactory.makeWanRepository() }

    private val _articleList: MutableLiveData<PageList> by lazy {
        MutableLiveData<PageList>()
    }

    // 对外暴露不可变的 LiveData，只能查询
    val articleList: LiveData<PageList> = _articleList

    val onRefreshListener: (RefreshLayout) -> Unit = {
        getArticleList2(true)
    }

    val onLoadMoreListener: (RefreshLayout) -> Unit = {
        getArticleList2(false)
    }


    private fun getArticleList2(isRefresh: Boolean = false) {
        when (isRefresh) {
            true -> curPage = 0
            false -> curPage++
        }
        requestOnlySuccess({ repository.getArticleList2(curPage) }, _articleList)
        finishRefresh(_articleList.value, isRefresh)
    }

    fun autoRefresh() {
        requestOnlySuccess({ repository.getArticleList2(0) }, _articleList,
            isShowLoadingView = true,
            isShowErrorView = true
        )
    }

}